let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
const moment = require("moment");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_COOPERATE_REQUIREMENT";
const ohana_instance = new ohana(tableName);
const tableName_1 = "SAP_JIANGDU_COOPERATE_REQUIREMENT_RECORD";
const ohana_instance_record = new ohana(tableName_1);
const ohana_instance_multi = new ohana("SAP_JIANGDU_MULTI_RECIPIENTS");

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

router.get("/countTopPublisher", async (req, res, next) => {
    // #swagger.tags = ['协同']
    // #swagger.summary = '获得前五个提供给对方的公司'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    getTopPublisher(user.user_id)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});
async function getTopPublisher(user_id) {
    const allCo = await ohana_instance_multi.find({
        RECIPIENT_ID: user_id
    })
    if (allCo.length > 0) {
        var checkList = [];
        allCo.map(one => {
            checkList.push(one.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID)
        })
        console.log(checkList);
        var sqlTest = "select top 5 count(*) as TOTAL,PUBLISHER,COMPANY_NAME from  	((SELECT  A.COOPERATE_REQUIREMENT_ID,A.PUBLISHER, B.COMPANY_NAME   FROM SAP_JIANGDU_COOPERATE_REQUIREMENT AS A  LEFT OUTER JOIN SAP_JIANGDU_USERS_REGISTERED AS B  ON A.PUBLISHER = B.USER_ID)  ) where COOPERATE_REQUIREMENT_ID in ("
        checkList.map((one, index) => {
            sqlTest += "'" + one + "'";
            if (index != checkList.length - 1) {
                sqlTest += ","
            }
        })

        sqlTest += ") group by PUBLISHER,COMPANY_NAME order by TOTAL desc"
        console.log(sqlTest)
        const supplier = await ohana_instance.raw(sqlTest);
        return supplier;

    } else {
        return []
    }


}
router.get("/countTopSupplier", async (req, res, next) => {
    // #swagger.tags = ['协同']
    // #swagger.summary = '获得前五个供应商'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    getTopSupplier(user.user_id)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getTopSupplier(user_id) {
    const allCo = await ohana_instance.find({
        PUBLISHER: user_id
    })
    if (allCo.length > 0) {
        var checkList = [];
        allCo.map(one => {
            checkList.push(one.COOPERATE_REQUIREMENT_ID)
        })
        console.log(checkList);
        var sqlTest = "select top 5 count(*) as TOTAL,RECIPIENT_ID,COMPANY_NAME from  	((SELECT  A.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID,A.RECIPIENT_ID, B.COMPANY_NAME   FROM SAP_JIANGDU_MULTI_RECIPIENTS AS A  LEFT OUTER JOIN SAP_JIANGDU_USERS_REGISTERED AS B  ON A.RECIPIENT_ID = B.USER_ID)  ) where COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID in ("
        checkList.map((one, index) => {
            sqlTest += "'" + one + "'";
            if (index != checkList.length - 1) {
                sqlTest += ","
            }
        })

        sqlTest += ") group by RECIPIENT_ID,COMPANY_NAME order by TOTAL desc"
        console.log(sqlTest)
        const supplier = await ohana_instance.raw(sqlTest);
        return supplier;

    } else {
        return []
    }


}


router.get("/countPubHis", async (req, res, next) => {
    // #swagger.tags = ['协同']
    // #swagger.summary = '历史12个月，每个月的发布需求个数趋势'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    getcountPubHis(user.user_id)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getcountPubHis(USER_ID) {
    let result = [];
    for (let i = 11; i >= 0; i--) {
        let startDate = moment().add(-i, "months").format("YYYY-MM");
        let endDate = moment()
            .add(-i + 1, "months")
            .format("YYYY-MM");
        sqlString =
            "select count(*) as total from SAP_JIANGDU_COOPERATE_REQUIREMENT WHERE PUBLISHER = '" +
            USER_ID +
            "' AND CREATED_AT >= '" +
            startDate +
            "' AND CREATED_AT < '" +
            endDate +
            "'";
        let pb_result = await ohana_instance.raw(sqlString);
        result.push(pb_result[0].TOTAL);
    }
    return result;
}

router.get("/countRecHis", async (req, res, next) => {
    // #swagger.tags = ['协同']
    // #swagger.summary = '历史12个月，每个月的满足供应个数趋势'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    getcountRecHis(user.user_id)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getcountRecHis(USER_ID) {
    let result = [];
    for (let i = 11; i >= 0; i--) {
        let startDate = moment().add(-i, "months").format("YYYY-MM");
        let endDate = moment()
            .add(-i + 1, "months")
            .format("YYYY-MM");
        sqlString =
            "select count(*) as total from SAP_JIANGDU_COOPERATE_REQUIREMENT as CO inner join SAP_JIANGDU_MULTI_RECIPIENTS as A1 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = CO.COOPERATE_REQUIREMENT_ID WHERE A1.RECIPIENT_ID  ='" +
            USER_ID +
            "' AND CREATED_AT >= '" +
            startDate +
            "' AND CREATED_AT < '" +
            endDate +
            "'";
        let re_result = await ohana_instance.raw(sqlString);
        result.push(re_result[0].TOTAL);
    }
    return result;
}

router.get("/countByIndustry", async (req, res, next) => {
    // #swagger.tags = ['协同']
    // #swagger.summary = '按照行业 协作企业 计数'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    getCountByIndustry(user.user_id)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getCountByIndustry(USER_ID) {
    let allCooperators = await getCooperateData(USER_ID);
    let result = {};
    for (let index = 0; index < allCooperators.length; index++) {
        const element = allCooperators[index];
        if (!result[element.INDUSTRY]) {
            result[element.INDUSTRY] = 1;
        } else {
            result[element.INDUSTRY] += 1;
        }
    }
    return result;
}

router.get("/requestCount", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '当年供应商申请物资需求个数总计'
    // #swagger.description = '需要JWT的userid作为publisher一个参数作为recepient，一个status参数，eg：当年供应商申请物资需求已完成总计'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    let { RECIPIENT, STATUS } = req.query;
    if (RECIPIENT) {
        payload.RECIPIENT = RECIPIENT;
    }
    if (STATUS) {
        payload.STATUS = STATUS;
    }
    payload.PUBLISHER = user.user_id;

    getRequestCountData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getRequestCountData(condition) {
    let result = [];
    if (!condition) {
        result = "请登录";
    } else {
        result = await ohana_instance.count(condition);
    }
    result = { COUNT: result[0]["COUNT(*)"] };
    return result;
}

router.get("/single", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '根据UUID获取'
    // #swagger.description = '不需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    let payload = {};
    let { COOPERATE_REQUIREMENT_ID } = req.query;
    payload.COOPERATE_REQUIREMENT_ID = COOPERATE_REQUIREMENT_ID;

    getSingleData(payload)
        .then((result) => {
            if (result.length == 0) {
                res.send(result);
            }
            let count = 0;
            result.forEach(async (element) => {
                element.recipients = [];
                let recipients = await ohana_instance_multi.find({
                    COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID:
                        element.COOPERATE_REQUIREMENT_ID,
                });
                await recipients.forEach((item) => {
                    element.recipients.push(item);
                });
                count++;
                if (count == result.length) {
                    res.send(result);
                }
            });
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getSingleData(condition) {
    let result = [];
    if (!condition) {
        result = "请给出UUID";
    } else {
        result = await ohana_instance.find(condition);
    }
    return result;
}

router.get("/publisher", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '获取publisher是自己的列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    let { TYPE, STATUS } = req.query;
    if (TYPE) {
        payload.TYPE = TYPE;
    }
    if (STATUS) {
        payload.STATUS = STATUS;
    }
    payload.PUBLISHER = user.user_id;

    getData(payload)
        .then((result) => {
            if (result.length == 0) {
                res.send(result);
            }
            let count = 0;
            result.forEach(async (element) => {
                element.recipients = [];
                let recipients = await ohana_instance_multi.find({
                    COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID:
                        element.COOPERATE_REQUIREMENT_ID,
                });
                await recipients.forEach((item) => {
                    element.recipients.push(item);
                });
                count++;
                if (count == result.length) {
                    res.send(result);
                }
            });
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.get("/recipient", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '获取recipient是自己的列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    let { TYPE, STATUS } = req.query;
    if (TYPE) {
        payload.TYPE = TYPE;
    }
    if (STATUS) {
        payload.STATUS = STATUS;
    }
    payload.RECIPIENT_ID = user.user_id;

    getRecipientData(payload)
        .then((result) => {
            if (result.length == 0) {
                res.send(result);
            }
            let count = 0;
            result.forEach(async (element) => {
                element.recipients = [];
                let recipients = await ohana_instance_multi.find({
                    COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID:
                        element.COOPERATE_REQUIREMENT_ID,
                });
                await recipients.forEach((item) => {
                    element.recipients.push(item);
                });
                count++;
                if (count == result.length) {
                    res.send(result);
                }
            });
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getRecipientData(condition) {
    let result = [];
    if (condition.STATUS && condition.TYPE) {
        result = await ohana_instance_multi.raw(
            'SELECT A1.MULTI_RECIPIENTS_ID, A1.RECIPIENT_ID, A2.* FROM "SAP_JIANGDU_MULTI_RECIPIENTS" as A1 LEFT JOIN "SAP_JIANGDU_COOPERATE_REQUIREMENT" as A2 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = A2.COOPERATE_REQUIREMENT_ID WHERE A1.RECIPIENT_ID  =\'' +
            condition.RECIPIENT_ID +
            "' AND A2.STATUS = '" +
            condition.STATUS +
            "' AND A2.TYPE = '" +
            condition.TYPE +
            "'"
        );
    } else if (condition.STATUS) {
        result = await ohana_instance_multi.raw(
            'SELECT A1.MULTI_RECIPIENTS_ID, A1.RECIPIENT_ID, A2.* FROM "SAP_JIANGDU_MULTI_RECIPIENTS" as A1 LEFT JOIN "SAP_JIANGDU_COOPERATE_REQUIREMENT" as A2 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = A2.COOPERATE_REQUIREMENT_ID WHERE A1.RECIPIENT_ID  =\'' +
            condition.RECIPIENT_ID +
            "' AND A2.STATUS = '" +
            condition.STATUS +
            "'"
        );
    } else if (condition.TYPE) {
        result = await ohana_instance_multi.raw(
            'SELECT A1.MULTI_RECIPIENTS_ID, A1.RECIPIENT_ID, A2.* FROM "SAP_JIANGDU_MULTI_RECIPIENTS" as A1 LEFT JOIN "SAP_JIANGDU_COOPERATE_REQUIREMENT" as A2 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = A2.COOPERATE_REQUIREMENT_ID WHERE A1.RECIPIENT_ID  =\'' +
            condition.RECIPIENT_ID +
            "' AND A2.TYPE = '" +
            condition.TYPE +
            "'"
        );
    } else {
        result = await ohana_instance_multi.raw(
            'SELECT A1.MULTI_RECIPIENTS_ID, A1.RECIPIENT_ID, A2.* FROM "SAP_JIANGDU_MULTI_RECIPIENTS" as A1 LEFT JOIN "SAP_JIANGDU_COOPERATE_REQUIREMENT" as A2 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = A2.COOPERATE_REQUIREMENT_ID WHERE A1.RECIPIENT_ID  =\'' +
            condition.RECIPIENT_ID +
            "'"
        );
    }

    return result;
}

router.get("/cooperate", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '获取和我协作的公司列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    getCooperateData(user.user_id)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getCooperateData(data) {
    let finalResult = [];
    let co_recipient_is_me = await getReData(data);
    finalResult = finalResult.concat(co_recipient_is_me);
    for (let index = 0; index < co_recipient_is_me.length; index++) {
        const element = co_recipient_is_me[index];
        let another_recipient = await getAnotherReData(
            element.COOPERATE_REQUIREMENT_ID
        );
        finalResult = finalResult.concat(another_recipient);
    }
    let co_publisher_is_me = await getPbData(data);
    finalResult = finalResult.concat(co_publisher_is_me);
    for (let i = 0, len = finalResult.length; i < len; i++) {
        for (let j = i + 1, len = finalResult.length; j < len; j++) {
            if (finalResult[i].USER_ID === finalResult[j].USER_ID) {
                finalResult.splice(j, 1);
                j--; // 每删除一个数j的值就减1
                len--; // j值减小时len也要相应减1（减少循环次数，节省性能）
            }
        }
    }
    return finalResult;
}
async function getReData(data) {
    sqlString =
        "select USER.CAP, USER.USER_ID, USER.INDUSTRY, USER.COMPANY_NAME ,CO.PUBLISHER, CO.COOPERATE_REQUIREMENT_ID, A1.RECIPIENT_ID from SAP_JIANGDU_COOPERATE_REQUIREMENT as CO inner join  " +
        constants.REGISTEDUSERSTABLE +
        ' as USER on CO.PUBLISHER = USER.USER_ID inner join "SAP_JIANGDU_MULTI_RECIPIENTS" as A1 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = CO.COOPERATE_REQUIREMENT_ID WHERE A1.RECIPIENT_ID  =\'' +
        data +
        "'";
    let re_result = await ohana_instance.raw(sqlString);
    return re_result;
}
async function getPbData(data) {
    sqlString =
        'select USER.CAP, USER.USER_ID, USER.INDUSTRY, USER.COMPANY_NAME ,CO.PUBLISHER, CO.COOPERATE_REQUIREMENT_ID, A1.RECIPIENT_ID from SAP_JIANGDU_COOPERATE_REQUIREMENT as CO inner join "SAP_JIANGDU_MULTI_RECIPIENTS" as A1 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = CO.COOPERATE_REQUIREMENT_ID inner join ' +
        constants.REGISTEDUSERSTABLE +
        " as USER on A1.RECIPIENT_ID = USER.USER_ID WHERE CO.PUBLISHER ='" +
        data +
        "'";
    let pb_result = await ohana_instance.raw(sqlString);
    return pb_result;
}

async function getAnotherReData(CO_ID) {
    sqlString =
        'select USER.CAP, USER.USER_ID, USER.INDUSTRY, USER.COMPANY_NAME ,CO.PUBLISHER, CO.COOPERATE_REQUIREMENT_ID, A1.RECIPIENT_ID from SAP_JIANGDU_COOPERATE_REQUIREMENT as CO inner join "SAP_JIANGDU_MULTI_RECIPIENTS" as A1 ON A1.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = CO.COOPERATE_REQUIREMENT_ID inner join ' +
        constants.REGISTEDUSERSTABLE +
        " as USER on A1.RECIPIENT_ID = USER.USER_ID WHERE CO.COOPERATE_REQUIREMENT_ID='" +
        CO_ID +
        "'";
    let pb_result = await ohana_instance.raw(sqlString);
    return pb_result;
}

router.get("/history", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '获取协作历史'
    // #swagger.description = '根据COOPERATE_REQUIREMENT_ID获取历史数据，需要JWT token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }
    let payload = {};
    let { COOPERATE_REQUIREMENT_ID } = req.query;
    payload.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID =
        COOPERATE_REQUIREMENT_ID;

    getHisData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getHisData(condition) {
    let result = [];
    if (!condition.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID) {
        result = "请输入参数：COOPERATE_REQUIREMENT_ID";
    } else {
        result = await ohana_instance_record.find(condition);
    }
    return result;
}

router.post("/assign", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.description = '需要JWT Token'
    // #swagger.summary = '分配任务给recipients'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/cooperate_assign"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let { data } = req.body;
    let COOPERATE_REQUIREMENT_ID = data.COOPERATE_REQUIREMENT_ID;
    let RECIPIENTS = data.RECIPIENTS;
    insertRecipients(RECIPIENTS, COOPERATE_REQUIREMENT_ID)
        .then((result) => {
            if (result > 0) {
                res.sendStatus(200);
            } else {
                res.status(400).send({ message: "数据错误" });
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function insertRecipients(recipients, COOPERATE_REQUIREMENT_ID) {
    let result1 = await ohana_instance.update(
        {
            COOPERATE_REQUIREMENT_ID: COOPERATE_REQUIREMENT_ID,
        },
        { STATUS: "assigned", TYPE: "incident" }
    );
    for (let i = 0; i < recipients.length; i++) {
        let data = {};
        data.RECIPIENT_ID = recipients[i];
        data.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID =
            COOPERATE_REQUIREMENT_ID;
        data.MULTI_RECIPIENTS_ID = uunewid.v4();
        await ohana_instance_multi.insert(data);
    }
    return result1;
}

router.post("/", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.description = '需要JWT Token'
    // #swagger.summary = '插入列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/cooperate_add"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let { data } = req.body;
    //创建接口的时候publisher和operator都是调用接口的人
    data.PUBLISHER = user.user_id;
    data.OPERATOR = user.user_id;
    insertData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.put("/", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '更新列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/cooperate_update"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let { data } = req.body;
    //修改接口的时候operator是调用接口的人
    data.OPERATOR = user.user_id;
    //删除不需要的字段
    delete data.RECIPIENT_ID;
    delete data.recipients;
    delete data.MULTI_RECIPIENTS_ID;
    updateData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['协同']
    // #swagger.summary = '删除列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/cooperate_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    deleteData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getData(condition) {
    let result = await ohana_instance.find(condition);
    return result;
}

async function insertData(data) {
    //在COOPERATE_REQUIREMENT表中插入data
    data.COOPERATE_REQUIREMENT_ID = uunewid.v4();
    let result = await ohana_instance.insert(data);

    //根据本次data在RECORD表插入一条数据
    // data.COOPERATE_REQUIREMENT_RECORD_ID = uunewid.v4();
    // data.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID = data.COOPERATE_REQUIREMENT_ID;
    // delete data.COOPERATE_REQUIREMENT_ID;
    // data.CREATED_AT = data.UPDATED_AT;
    // delete data.UPDATED_AT;
    // await ohana_instance_record.insert(data);
    return result;
}

async function updateData(data) {
    let result = await ohana_instance.update(
        {
            COOPERATE_REQUIREMENT_ID: data.COOPERATE_REQUIREMENT_ID,
        },
        data
    );
    data.COOPERATE_REQUIREMENT_RECORD_ID = uunewid.v4();
    data.COOPERATE_REQUIREMENT_ID_COOPERATE_REQUIREMENT_ID =
        data.COOPERATE_REQUIREMENT_ID;
    delete data.COOPERATE_REQUIREMENT_ID;
    data.CREATED_AT = data.UPDATED_AT;
    delete data.UPDATED_AT;
    await ohana_instance_record.insert(data);
    return result;
}

async function deleteData(data) {
    let result = await ohana_instance.raw(
        'delete from "' +
        tableName +
        "\" where COOPERATE_REQUIREMENT_ID = '" +
        data.COOPERATE_REQUIREMENT_ID +
        "'"
    );
    return result;
}

module.exports = router;
